//
//  MusicPlayerView.swift
//  NDAi
//
//  Created by 丸子 on 2024/7/25.
//

import UIKit
import YYText

class MusicPlayerView: UIView {
    lazy var backIV: UIImageView = {
        let imageView = UIImageView()
        imageView.clipsToBounds = true
        imageView.contentMode = .scaleAspectFill
        imageView.backgroundColor = UIColor(hexString: "#000000", transparency: 0.3)
        return imageView
    }()
    
    lazy var backBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.imageForNormal = UIImage(named: "icon_video_back")
        return button
    }()
    
    lazy var rightBtn: UIButton = {
        let rightBtn = UIButton(type: .custom)
        rightBtn.setTitle("定制音乐", for: .normal)
        rightBtn.normalTitleColor = .white
        rightBtn.allRound(12)
        rightBtn.titleLabel?.font = UIFont.pingFangSCRegular(ofSize: 14)
        return rightBtn
    }()
    
    lazy var historyBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.imageForNormal = UIImage(named: "icon_music_history")
        return button
    }()
    
    lazy var navTitleLb: UILabel = {
        let label = UILabel()
        label.text = "生成结果"
        label.textColor = .white
        label.font = UIFont.pingFangSCRegular(ofSize: 16)
        return label
    }()
    
    lazy var coverIV: UIImageView = {
        let imageView = UIImageView()
        imageView.clipsToBounds = true
        imageView.contentMode = .scaleAspectFill
        imageView.image = UIImage(named: "icon_music_def")
        imageView.allRound(110)
        return imageView
    }()
    
    lazy var titleLb: UILabel = {
        let label = UILabel()
        label.text = "我的女朋友白雪(My Dragon Lady)"
        label.textColor = .white
        label.font = UIFont.pingFangSCRegular(ofSize: 18)
        label.textAlignment = .center
        return label
    }()
    
    lazy var descLb: UILabel = {
        let label = UILabel()
        label.text = "我的女朋友白雪(My Dragon Lady)"
        label.textColor = .white.withAlphaComponent(0.5)
        label.font = UIFont.pingFangSCRegular(ofSize: 12)
        label.textAlignment = .center
        return label
    }()
    
    lazy var timeLb: UILabel = {
        let label = UILabel()
        label.text = "2024-06-03 19:34:12"
        label.textColor = .white.withAlphaComponent(0.5)
        label.font = UIFont.pingFangSCRegular(ofSize: 11)
        label.textAlignment = .center
        return label
    }()
    
    lazy var lyricView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hexString: "#000000", transparency: 0.2)
        view.allRound(8)
        return view
    }()
    
    lazy var saveBtn: UIButton = {
       let button = UIButton(type: .custom)
       button.titleForNormal = "下载"
       button.titleFont = UIFont.pingFangSCRegular(ofSize: 16)
        button.backgroundColor = UIColor(hexString: "#000000", transparency: 0.3)
       button.allRound(24)
       return button
   }()
    
    lazy var descTextView: YYTextView = {
        let view = YYTextView()
        view.textContainerInset = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
//        view.placeholderText = "请描述你想要生成的歌曲\n如：给我的女朋友白雪写一首歌，祝她大学毕业"
        view.placeholderFont = UIFont.pingFangSCRegular(ofSize: 12)
        view.placeholderTextColor = Theme.color.text_d3
        view.textColor = .white
//        view.delegate = self
        view.font = UIFont.pingFangSCRegular(ofSize: 12)
        view.isEditable = false // 禁止用户编辑
        view.isScrollEnabled = true // 允许滚动
        return view
    }()
    
    lazy var playBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "icon_musicd_player"), for: .normal)
        button.setImage(UIImage(named: "icon_musicd_pause"), for: .selected)
        return button
    }()
    
    lazy var musicSlider: MusicCustomSlider = {
        let slider = MusicCustomSlider()
        slider.minimumValue = 0
        slider.maximumValue = 1
        slider.value = 0
        slider.setThumbImage(UIImage(), for: .normal)
        slider.setThumbImage(UIImage(), for: .highlighted)
        slider.minimumTrackTintColor = .white
        slider.maximumTrackTintColor = UIColor(hexString: "#333333", transparency: 0.2)
        return slider
    }()
    
    lazy var cuLb: UILabel = {
        let label = UILabel()
        label.text = "00:00"
        label.textColor = .white
        label.font = UIFont.pingFangSCRegular(ofSize: 12)
        return label
    }()
    
    lazy var toLb: UILabel = {
        let label = UILabel()
        label.text = "00:00"
        label.textColor = .white
        label.font = UIFont.pingFangSCRegular(ofSize: 12)
        return label
    }()
     
    lazy var shareBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.imageForNormal = UIImage(named: "icon_music_share")
        return button
    }()
    
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        self.addSubview(backIV)  
        self.addSubviews([backBtn, historyBtn, navTitleLb, rightBtn])
        self.addSubviews([coverIV, titleLb, descLb, timeLb, lyricView, musicSlider, cuLb, toLb, playBtn])
        lyricView.addSubviews([descTextView, shareBtn])
        self.addSubviews([saveBtn])
        self.backIV.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        backBtn.snp.makeConstraints { make in
            make.top.equalTo(self.safeAreaLayoutGuide.snp.top).offset(10)
            make.leading.equalTo(16)
            make.width.height.equalTo(30)
        }
        
        historyBtn.snp.makeConstraints { make in
            make.centerY.equalTo(backBtn)
            make.leading.equalTo(backBtn.snp.trailing).offset(10)
            make.width.height.equalTo(30)
        }
        
        navTitleLb.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(backBtn)
        }
        
        rightBtn.snp.makeConstraints { make in
            make.centerY.equalTo(navTitleLb)
            make.trailing.equalToSuperview().offset(-15)
        }
        
        coverIV.snp.makeConstraints { make in
            make.top.equalTo(navTitleLb.snp.bottom).offset(30)
            make.centerX.equalToSuperview()
            make.height.width.equalTo(220)
        }
        
        titleLb.snp.makeConstraints { make in
            make.top.equalTo(coverIV.snp.bottom).offset(12)
            make.leading.trailing.equalToSuperview().inset(24)
        }
        
        descLb.snp.makeConstraints { make in
            make.top.equalTo(titleLb.snp.bottom).offset(2)
            make.leading.trailing.equalToSuperview().inset(24)
        }
        
        timeLb.snp.makeConstraints { make in
            make.top.equalTo(descLb.snp.bottom).offset(2)
            make.leading.trailing.equalToSuperview().inset(24)
        }
        
        lyricView.snp.makeConstraints { make in
            make.top.equalTo(timeLb.snp.bottom).offset(4)
            make.leading.trailing.equalToSuperview().inset(50)
            make.height.equalTo(220)
        }
        shareBtn.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-12)
            make.bottom.equalToSuperview().offset(-12)
            make.width.height.equalTo(30)
        }
        
        descTextView.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            make.bottom.equalTo(shareBtn.snp.top).offset(-0)
        }
        
        musicSlider.snp.makeConstraints { make in
            make.top.equalTo(lyricView.snp.bottom).offset(20)
            make.leading.trailing.equalToSuperview().inset(70)
            make.height.equalTo(2)
        }
        
        cuLb.snp.makeConstraints { make in
            make.centerY.equalTo(musicSlider)
            make.trailing.equalTo(musicSlider.snp.leading).offset(-6)
        }
        
        toLb.snp.makeConstraints { make in
            make.centerY.equalTo(musicSlider)
            make.leading.equalTo(musicSlider.snp.trailing).offset(12)
        }
        
        playBtn.snp.makeConstraints { make in
            make.centerX.centerY.equalTo(coverIV)
//            make.top.equalTo(musicSlider.snp.bottom).offset(30)
            make.width.height.equalTo(58)
        }
        
        
        saveBtn.snp.makeConstraints { make in
            make.top.equalTo(musicSlider.snp.bottom).offset(40)
            make.leading.equalToSuperview().offset(15)
            make.trailing.equalToSuperview().offset(-15)
            make.height.equalTo(48)
        }
    }
    
    func setup(model:MusicModel?) {
        guard let model = model else { return }
//        backIV.sd_setImage(with: URL(string: model.cover_url))
        coverIV.sd_setImage(with: URL(string: model.cover_url))
        self.titleLb.text = model.title ?? model.music_name
        self.descLb.text = model.lyric_desc
        self.timeLb.text = model.create_time
        self.descTextView.text = model.music_lyric
        
        // 使用 SDWebImage 下载图片
        if let url = URL(string: model.cover_url) {
            backIV.sd_setImage(with: url, completed: { [weak self] (image, error, cacheType, imageURL) in
                guard let self = self, let image = image else { return }
                // 对图片应用高斯模糊效果
                let blurredImage = self.applyBlurEffect(image: image)
                // 对模糊后的图片应用透明度效果
                self.backIV.image = blurredImage
            })
        }
    }
    // 对图片应用高斯模糊效果
     func applyBlurEffect(image: UIImage) -> UIImage? {
         guard let ciImage = CIImage(image: image) else { return nil }
         let blurFilter = CIFilter(name: "CIGaussianBlur")
         blurFilter?.setValue(ciImage, forKey: kCIInputImageKey)
         blurFilter?.setValue(10.0, forKey: kCIInputRadiusKey)  // 调整模糊半径
         
         guard let outputCIImage = blurFilter?.outputImage else { return nil }
         let context = CIContext()
         if let cgImage = context.createCGImage(outputCIImage, from: ciImage.extent) {
             return UIImage(cgImage: cgImage)
         }
         return nil
     }
     
     // 对模糊后的图片应用透明度效果
     func applyTransparency(image: UIImage?, alpha: CGFloat) -> UIImage? {
         guard let image = image else { return nil }
         UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
         let context = UIGraphicsGetCurrentContext()
         let rect = CGRect(origin: CGPoint.zero, size: image.size)
         
         context?.scaleBy(x: 1, y: -1)
         context?.translateBy(x: 0, y: -rect.size.height)
         
         context?.setBlendMode(.normal)
         context?.setAlpha(alpha)
         context?.draw(image.cgImage!, in: rect)
         
         let transparentImage = UIGraphicsGetImageFromCurrentImageContext()
         UIGraphicsEndImageContext()
         
         return transparentImage
     }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}



class MusicCustomSlider: UISlider {
    
    var sliderHeight: CGFloat = 2.0
    
    override func minimumValueImageRect(forBounds bounds: CGRect) -> CGRect {
        return self.bounds
    }
    
    override func maximumValueImageRect(forBounds bounds: CGRect) -> CGRect {
        return self.bounds
    }
    
    // 控制slider的宽和高，这个方法才是真正的改变slider滑道的高的
    override func trackRect(forBounds bounds: CGRect) -> CGRect {
        let rect = super.trackRect(forBounds: bounds)
        layer.cornerRadius = sliderHeight/2
        return CGRect.init(x: rect.origin.x, y: (bounds.size.height-sliderHeight)/2, width: bounds.size.width, height: sliderHeight)
    }
    
    // 改变滑块的触摸范围
    override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect {
        return super.thumbRect(forBounds: bounds, trackRect: rect, value: value)
    }
}

class HomeMusicPlayerView: UIView {
    lazy var backIV: UIImageView = {
        let imageView = UIImageView()
        imageView.clipsToBounds = true
        imageView.contentMode = .scaleAspectFill
        imageView.backgroundColor = UIColor(hexString: "#000000", transparency: 0.3)
        return imageView
    }()
    
    lazy var backBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.imageForNormal = UIImage(named: "icon_video_back")
        return button
    }()
    
    lazy var rightBtn: UIButton = {
        let rightBtn = UIButton(type: .custom)
        rightBtn.normalImage = UIImage(named: "icon_music_share")
        rightBtn.normalTitleColor = .white
        rightBtn.allRound(12)
        rightBtn.titleLabel?.font = UIFont.pingFangSCRegular(ofSize: 14)
        return rightBtn
    }()
    
    lazy var historyBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.imageForNormal = UIImage(named: "icon_music_history")
        button.isHidden = true
        return button
    }()
    
    lazy var navTitleLb: UILabel = {
        let label = UILabel()
        label.text = "音乐详情"
        label.textColor = .white
        label.font = UIFont.pingFangSCRegular(ofSize: 16)
        return label
    }()
    
    lazy var coverIV: UIImageView = {
        let imageView = UIImageView()
        imageView.clipsToBounds = true
        imageView.contentMode = .scaleAspectFill
        imageView.image = UIImage(named: "icon_music_def")
        imageView.allRound(110)
        return imageView
    }()
    
    lazy var titleLb: UILabel = {
        let label = UILabel()
        label.text = "我的女朋友白雪(My Dragon Lady)"
        label.textColor = .white
        label.font = UIFont.pingFangSCRegular(ofSize: 18)
        label.textAlignment = .center
        return label
    }()
    
    lazy var descLb: UILabel = {
        let label = UILabel()
        label.text = "我的女朋友白雪(My Dragon Lady)"
        label.textColor = .white.withAlphaComponent(0.5)
        label.font = UIFont.pingFangSCRegular(ofSize: 12)
        label.textAlignment = .center
        return label
    }()
    
    lazy var timeLb: UILabel = {
        let label = UILabel()
        label.text = "2024-06-03 19:34:12"
        label.textColor = .white.withAlphaComponent(0.5)
        label.font = UIFont.pingFangSCRegular(ofSize: 11)
        label.textAlignment = .center
        return label
    }()
    
    lazy var lyricView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hexString: "#000000", transparency: 0.2)
        view.allRound(8)
        return view
    }()
    
    
    
    lazy var descTextView: YYTextView = {
        let view = YYTextView()
        view.textContainerInset = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
//        view.placeholderText = "请描述你想要生成的歌曲\n如：给我的女朋友白雪写一首歌，祝她大学毕业"
        view.placeholderFont = UIFont.pingFangSCRegular(ofSize: 12)
        view.placeholderTextColor = Theme.color.text_d3
        view.textColor = .white
//        view.delegate = self
        view.font = UIFont.pingFangSCRegular(ofSize: 12)
        view.isEditable = false // 禁止用户编辑
        view.isScrollEnabled = true // 允许滚动
        return view
    }()
    
    lazy var playBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "icon_musicd_player"), for: .normal)
        button.setImage(UIImage(named: "icon_musicd_pause"), for: .selected)
        return button
    }()
    
    lazy var musicSlider: MusicCustomSlider = {
        let slider = MusicCustomSlider()
        slider.minimumValue = 0
        slider.maximumValue = 1
        slider.value = 0
        slider.setThumbImage(UIImage(), for: .normal)
        slider.setThumbImage(UIImage(), for: .highlighted)
        slider.minimumTrackTintColor = .white
        slider.maximumTrackTintColor = UIColor(hexString: "#333333", transparency: 0.2)
        return slider
    }()
    
    lazy var cuLb: UILabel = {
        let label = UILabel()
        label.text = "00:00"
        label.textColor = .white
        label.font = UIFont.pingFangSCRegular(ofSize: 12)
        return label
    }()
    
    lazy var toLb: UILabel = {
        let label = UILabel()
        label.text = "00:00"
        label.textColor = .white
        label.font = UIFont.pingFangSCRegular(ofSize: 12)
        return label
    }()
     
     lazy var saveBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleForNormal = "下载"
        button.titleFont = UIFont.pingFangSCRegular(ofSize: 16)
         button.backgroundColor = UIColor(hexString: "#000000", transparency: 0.3)
        button.allRound(24)
        return button
    }()
    
     lazy var likeBtn: UIButton = {
        let button = UIButton(type: .custom)
         button.titleColorForNormal = .white
        button.normalImage = UIImage(named: "icon_com_likeNor")
        button.selectedImage = UIImage(named: "icon_com_likeSel")
        button.titleFont = UIFont.pingFangSCRegular(ofSize: 16)
         button.backgroundColor = UIColor(hexString: "#000000", transparency: 0.3)
        button.allRound(24)
        button.layoutButtonWithEdgeInsetsStyle(.Left, space: 8)
        return button
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        self.addSubview(backIV)
        self.addSubviews([backBtn, historyBtn, navTitleLb, rightBtn])
        self.addSubviews([coverIV, titleLb, descLb, timeLb, lyricView, musicSlider, cuLb, toLb, playBtn])
        lyricView.addSubviews([descTextView])
        self.addSubviews([saveBtn, likeBtn])
        self.backIV.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        backBtn.snp.makeConstraints { make in
            make.top.equalTo(self.safeAreaLayoutGuide.snp.top).offset(10)
            make.leading.equalTo(16)
            make.width.height.equalTo(30)
        }
        
        historyBtn.snp.makeConstraints { make in
            make.centerY.equalTo(backBtn)
            make.leading.equalTo(backBtn.snp.trailing).offset(10)
            make.width.height.equalTo(30)
        }
        
        navTitleLb.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(backBtn)
        }
        
        rightBtn.snp.makeConstraints { make in
            make.centerY.equalTo(navTitleLb)
            make.trailing.equalToSuperview().offset(-15)
        }
        
        coverIV.snp.makeConstraints { make in
            make.top.equalTo(navTitleLb.snp.bottom).offset(30)
            make.centerX.equalToSuperview()
            make.height.width.equalTo(220)
        }
        
        titleLb.snp.makeConstraints { make in
            make.top.equalTo(coverIV.snp.bottom).offset(12)
            make.leading.trailing.equalToSuperview().inset(24)
        }
        
        descLb.snp.makeConstraints { make in
            make.top.equalTo(titleLb.snp.bottom).offset(2)
            make.leading.trailing.equalToSuperview().inset(24)
        }
        
        timeLb.snp.makeConstraints { make in
            make.top.equalTo(descLb.snp.bottom).offset(2)
            make.leading.trailing.equalToSuperview().inset(24)
        }
        
        lyricView.snp.makeConstraints { make in
            make.top.equalTo(timeLb.snp.bottom).offset(4)
            make.leading.trailing.equalToSuperview().inset(50)
            make.height.equalTo(190)
        }
        
        descTextView.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            make.bottom.equalToSuperview().offset(0)
        }
        
        musicSlider.snp.makeConstraints { make in
            make.top.equalTo(lyricView.snp.bottom).offset(20)
            make.leading.trailing.equalToSuperview().inset(70)
            make.height.equalTo(2)
        }
        
        cuLb.snp.makeConstraints { make in
            make.centerY.equalTo(musicSlider)
            make.trailing.equalTo(musicSlider.snp.leading).offset(-6)
        }
        
        toLb.snp.makeConstraints { make in
            make.centerY.equalTo(musicSlider)
            make.leading.equalTo(musicSlider.snp.trailing).offset(12)
        }
        
        playBtn.snp.makeConstraints { make in
            make.centerX.centerY.equalTo(coverIV)
            make.width.height.equalTo(58)
        }
        
        likeBtn.snp.makeConstraints { make in
             make.top.equalTo(musicSlider.snp.bottom).offset(40)
              make.leading.equalTo(saveBtn.snp.trailing).offset(10)
              make.trailing.equalToSuperview().offset(-15)
              make.height.equalTo(48)
        }

        saveBtn.snp.makeConstraints { make in
            make.top.equalTo(musicSlider.snp.bottom).offset(40)
            make.leading.equalToSuperview().offset(15)
            make.height.equalTo(48)
            make.width.equalTo(likeBtn.snp.width)
        }
        
    }
    
    func setup(model:CommunityModel?) {
        guard let model = model else { return }
//        backIV.sd_setImage(with: URL(string: model.cover_url))
        coverIV.sd_setImage(with: URL(string: model.img_url))
        self.titleLb.text = model.title ?? ""
        self.descLb.text = model.music_lyric
        self.timeLb.text = model.create_time
        self.descTextView.text = model.music_lyric
        likeBtn.titleForNormal = model.like_count?.formatted
        likeBtn.isSelected = model.is_like == 1 ? true : false
        // 使用 SDWebImage 下载图片
        if let url = URL(string: model.img_url) {
            backIV.sd_setImage(with: url, completed: { [weak self] (image, error, cacheType, imageURL) in
                guard let self = self, let image = image else { return }
                // 对图片应用高斯模糊效果
                let blurredImage = self.applyBlurEffect(image: image)
                // 对模糊后的图片应用透明度效果
                self.backIV.image = blurredImage
            })
        }
    }
    func setupMs(model:MusicModel?) {
        guard let model = model else { return }
//        backIV.sd_setImage(with: URL(string: model.cover_url))
        coverIV.sd_setImage(with: URL(string: model.cover_url))
        self.titleLb.text = model.title ?? model.music_name
        self.descLb.text = model.lyric_desc
        self.timeLb.text = model.create_time
        self.descTextView.text = model.music_lyric
        
        // 使用 SDWebImage 下载图片
        if let url = URL(string: model.cover_url) {
            backIV.sd_setImage(with: url, completed: { [weak self] (image, error, cacheType, imageURL) in
                guard let self = self, let image = image else { return }
                // 对图片应用高斯模糊效果
                let blurredImage = self.applyBlurEffect(image: image)
                // 对模糊后的图片应用透明度效果
                self.backIV.image = blurredImage
            })
        }
    }
    // 对图片应用高斯模糊效果
     func applyBlurEffect(image: UIImage) -> UIImage? {
         guard let ciImage = CIImage(image: image) else { return nil }
         let blurFilter = CIFilter(name: "CIGaussianBlur")
         blurFilter?.setValue(ciImage, forKey: kCIInputImageKey)
         blurFilter?.setValue(10.0, forKey: kCIInputRadiusKey)  // 调整模糊半径
         
         guard let outputCIImage = blurFilter?.outputImage else { return nil }
         let context = CIContext()
         if let cgImage = context.createCGImage(outputCIImage, from: ciImage.extent) {
             return UIImage(cgImage: cgImage)
         }
         return nil
     }
     
     // 对模糊后的图片应用透明度效果
     func applyTransparency(image: UIImage?, alpha: CGFloat) -> UIImage? {
         guard let image = image else { return nil }
         UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
         let context = UIGraphicsGetCurrentContext()
         let rect = CGRect(origin: CGPoint.zero, size: image.size)
         
         context?.scaleBy(x: 1, y: -1)
         context?.translateBy(x: 0, y: -rect.size.height)
         
         context?.setBlendMode(.normal)
         context?.setAlpha(alpha)
         context?.draw(image.cgImage!, in: rect)
         
         let transparentImage = UIGraphicsGetImageFromCurrentImageContext()
         UIGraphicsEndImageContext()
         
         return transparentImage
     }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
